package com.quickcode.example.singleton;

import com.quickcode.annotation.Safe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 对实例3的补充，添加volatile防止cpu进行指令重排操作
 * Created by 张波 on 2019/10/23.
 */
@Safe
@Slf4j
public class SingletonExample4 {

    private volatile static SingletonExample4 instance = null;

    private SingletonExample4() {
        log.error("调用了构造方法创建了对象");
    }

    public static SingletonExample4 getInstance() {
        if (instance == null) {
            synchronized (SingletonExample4.class) {
                if (instance == null) {
                    instance = new SingletonExample4();
                }
            }

        }
        return instance;
    }

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 100; ++i) {
            executorService.execute(() -> {
                if(null == SingletonExample4.getInstance()) {
                    log.error("我取了个null值");
                }
            });
        }
        executorService.shutdown();
    }

}
